package git.determinal.template.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import git.determinal.template.domin.dto.SearchDto;
import git.determinal.template.domin.dto.TemplateDto;
import git.determinal.template.domin.view.TemplateView;
import git.determinal.template.mapper.TemplateMapper;
import git.determinal.template.model.Template;
import git.determinal.template.service.TemplateService;
import git.determinal.template.util.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Service
public class TemplateServiceImpl extends ServiceImpl<TemplateMapper, Template> implements TemplateService {

    @Override
    public void updateEntity(TemplateDto templateDto) {
        Timestamp nowTime = new Timestamp(System.currentTimeMillis());
        if (StringUtils.isNullOrEmpty(templateDto.getId())) {
            templateDto.setCreatedTime(nowTime);
            templateDto.setModifiedTime(nowTime);
            save(templateDto);
        } else {
            templateDto.setModifiedTime(nowTime);
            updateById(templateDto);
        }
    }

    @Override
    public void deleteEntity(String ids) {
        String[] idArr = ids.split(",");
        for (String id : idArr) {
            removeById(id);
        }
    }

    @Override
    public Page<TemplateView> pageContent(SearchDto searchDto) {
        // 取值
        Integer current = searchDto.getCurrent();
        Integer pageSize = searchDto.getPageSize();
        Date startTime = TimeUtils.string2Date(searchDto.getStartTime());
        Date endTime = TimeUtils.string2Date(searchDto.getEndTime());
        String searchContent = searchDto.getSearchContent();
        Page<Template> page = new Page<>(current, pageSize);
        // 查询
        Page<Template> pageRes = this.getBaseMapper().pageContent(page, startTime, endTime, searchContent);
        List<Template> templates = pageRes.getRecords();
        List<TemplateView> templateViews = new ArrayList<>();
        // 转换
        for (Template template : templates) {
            TemplateView templateView = new TemplateView();
            BeanUtils.copyProperties(template, templateView);
            templateViews.add(templateView);
        }
        // 存入
        Page<TemplateView> pageView = new Page<>();
        BeanUtils.copyProperties(pageRes, pageView);
        pageView.setRecords(templateViews);
        return  pageView;
    }

    @Override
    public TemplateView getEntity(String id) {
        TemplateView templateView = new TemplateView();
        Template template = getById(id);
        BeanUtils.copyProperties(template, templateView);
        return templateView;
    }

}

